import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart' show PopupMenuButton, PopupMenuItem;
import 'package:management_invoices/features/invoice/view_models/invoice_self_view_model.dart';
import 'package:provider/provider.dart';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

import 'package:management_invoices/core/models/invoice_self_model.dart';

class InvoiceSelfView extends StatelessWidget {
  const InvoiceSelfView({super.key});

  @override
  Widget build(BuildContext context) {
    final invoiceSelfViewModel = context.watch<InvoiceSelfViewModel>();
    if (invoiceSelfViewModel.isLoading) {
      return const Center(child: ProgressRing());
    }
    return SizedBox(
      width: double.infinity,
      height: double.infinity,
      child: Container(
        color: FluentTheme.of(context).scaffoldBackgroundColor, // 动态背景颜色
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.only(
                top: 10.0,
                left: 20.0,
                right: 20.0,
                bottom: 80.0,
              ),
              child: LayoutBuilder(
                builder: (context, constraints) {
                  final invoiceDataSource = InvoiceDataSource(
                    invoices: invoiceSelfViewModel.paginatedData,
                    context: context, // 传递 BuildContext
                  );

                  return SfDataGrid(
                    columnWidthMode: ColumnWidthMode.fill,
                    gridLinesVisibility: GridLinesVisibility.both,
                    headerGridLinesVisibility: GridLinesVisibility.both,
                    rowHeight: 60,
                    source: invoiceDataSource,
                    columns: [
                      GridColumn(
                        columnName: 'invoiceNum',
                        label: _buildHeader(context, '发票税号'),
                      ),
                      GridColumn(
                        columnName: 'invoiceType',
                        label: _buildHeader(context, '发票类型'),
                      ),
                      GridColumn(
                        columnName: 'invoiceDate',
                        label: _buildHeader(context, '开票日期'),
                      ),
                      GridColumn(
                        columnName: 'purchaserName',
                        label: _buildHeader(context, '购买物品'),
                      ),
                      GridColumn(
                        columnName: 'sellerName',
                        label: _buildHeader(context, '销售者'),
                      ),
                      GridColumn(
                        columnName: 'amountInFigures',
                        label: _buildHeader(context, '金额'),
                      ),
                      GridColumn(
                        columnName: 'button',
                        label: _buildHeader(context, '操作'),
                      ),
                    ],
                  );
                },
              ),
            ),
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: _buildPaginationControls(context),
            ),
            Positioned(
              right: 15,
              bottom: 10,
              child: Text(
                '总金额: ¥${invoiceSelfViewModel.totalAmount.toStringAsFixed(2)}',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color:
                      FluentTheme.of(context).brightness == Brightness.dark
                          ? Colors
                              .white // 深色模式下文字为白色
                          : Colors.black, // 浅色模式下文字为黑色
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader(BuildContext context, String text) {
    final theme = FluentTheme.of(context); // 使用传递的 BuildContext 获取主题

    return Center(
      child: Text(
        text,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontFamily: 'MSYH',
          color:
              theme.brightness == Brightness.dark
                  ? Colors
                      .white // 深色模式下表头文字为白色
                  : Colors.black, // 浅色模式下表头文字为黑色
        ),
      ),
    );
  }

  Widget _buildPaginationControls(BuildContext context) {
    final theme = FluentTheme.of(context); // 获取当前主题
    final invoiceSelfViewModel = context.watch<InvoiceSelfViewModel>();

    return Container(
      color:
          theme.brightness == Brightness.dark
              ? Colors.grey[220] // 深色模式下背景为深灰色
              : Colors.grey[100], // 浅色模式下背景为浅灰色
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Center(
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              MouseRegion(
                cursor: SystemMouseCursors.click,
                child: IconButton(
                  icon: Icon(
                    FluentIcons.chevron_left,
                    color:
                        theme.brightness == Brightness.dark
                            ? Colors
                                .white // 深色模式下图标为白色
                            : Colors.black, // 浅色模式下图标为黑色
                  ),
                  onPressed:
                      invoiceSelfViewModel.currentPage > 1
                          ? () => invoiceSelfViewModel.setCurrentPage(
                            invoiceSelfViewModel.currentPage - 1,
                          )
                          : null,
                ),
              ),
              const SizedBox(width: 10),
              Container(
                constraints: const BoxConstraints(maxWidth: 200),
                child: Text(
                  '第 ${invoiceSelfViewModel.currentPage} 页 / 共 ${invoiceSelfViewModel.totalPages} 页',
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              const SizedBox(width: 10),
              MouseRegion(
                cursor: SystemMouseCursors.click,
                child: IconButton(
                  icon: const Icon(FluentIcons.chevron_right),
                  onPressed:
                      invoiceSelfViewModel.currentPage <
                              invoiceSelfViewModel.totalPages
                          ? () => invoiceSelfViewModel.setCurrentPage(
                            invoiceSelfViewModel.currentPage + 1,
                          )
                          : null,
                ),
              ),
              const SizedBox(width: 20),
              MouseRegion(
                cursor: SystemMouseCursors.click,
                child: ConstrainedBox(
                  constraints: const BoxConstraints(maxWidth: 120),
                  child: ComboBox<int>(
                    value: invoiceSelfViewModel.itemsPerPage,
                    items: [
                      ComboBoxItem(
                        value: 10,
                        child: MouseRegion(
                          cursor: SystemMouseCursors.click,
                          child: Text('10 条/页'),
                        ),
                      ),
                      ComboBoxItem(
                        value: 20,
                        child: MouseRegion(
                          cursor: SystemMouseCursors.click,
                          child: Text('20 条/页'),
                        ),
                      ),
                      ComboBoxItem(
                        value: 50,
                        child: MouseRegion(
                          cursor: SystemMouseCursors.click,
                          child: Text('50 条/页'),
                        ),
                      ),
                    ],
                    onChanged: (value) {
                      if (value != null) {
                        invoiceSelfViewModel.setItemsPerPage(value);
                      }
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class InvoiceDataSource extends DataGridSource {
  InvoiceDataSource({
    required List<InvoiceModel> invoices,
    required this.context,
    this.showButton = true, // 默认不显示按钮
  }) {
    _invoices =
        invoices.map<DataGridRow>((invoice) {
          final cells = [
            DataGridCell<String>(
              columnName: 'invoiceNum',
              value: invoice.invoiceNum,
            ),
            DataGridCell<String>(
              columnName: 'invoiceType',
              value: invoice.invoiceType,
            ),
            DataGridCell<String>(
              columnName: 'invoiceDate',
              value: invoice.invoiceDate,
            ),
            DataGridCell<String>(
              columnName: 'purchaserName',
              value: invoice.purchaserName,
            ),
            DataGridCell<String>(
              columnName: 'sellerName',
              value: invoice.sellerName,
            ),
            DataGridCell<Decimal>(
              columnName: 'amountInFigures',
              value: invoice.amountInFigures,
            ),
          ];

          // 如果需要显示按钮列，则添加按钮列
          if (showButton) {
            cells.add(
              DataGridCell<Widget>(
                columnName: 'button',
                value: _buildPopupMenu(invoice),
              ),
            );
          }

          return DataGridRow(cells: cells);
        }).toList();
  }

  final BuildContext context; // 保存 BuildContext
  final bool showButton; // 控制是否显示按钮列
  List<DataGridRow> _invoices = [];

  Widget _buildPopupMenu(InvoiceModel invoice) {
    final invoiceSelfVM = context.watch<InvoiceSelfViewModel>();
    return PopupMenuButton<String>(
      onSelected: (value) {
        switch (value) {
          case 'edit':
            invoiceSelfVM.editInvoice(invoice, context);
            break;
          case 'delete':
            invoiceSelfVM.deleteInvoice(invoice, context);
            break;
        }
      },
      itemBuilder:
          (context) => [
            PopupMenuItem(
              value: 'edit',
              child: Row(
                children: const [
                  Icon(FluentIcons.edit, size: 16),
                  SizedBox(width: 8),
                  Text('编辑'),
                ],
              ),
            ),
            PopupMenuItem(
              value: 'delete',
              child: Row(
                children: const [
                  Icon(FluentIcons.delete, size: 16),
                  SizedBox(width: 8),
                  Text('删除'),
                ],
              ),
            ),
          ],
      child: const Icon(FluentIcons.more, size: 20),
    );
  }

  @override
  List<DataGridRow> get rows => _invoices;

  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    final theme = FluentTheme.of(context); // 使用传递的 BuildContext 获取主题

    return DataGridRowAdapter(
      cells:
          row.getCells().map<Widget>((dataGridCell) {
            if (dataGridCell.columnName == 'button') {
              // 如果是按钮列，直接渲染为 Widget
              return dataGridCell.value as Widget;
            }
            return Container(
              alignment: Alignment.center,
              padding: const EdgeInsets.all(8.0),
              child: Text(
                dataGridCell.value.toString(),
                overflow: TextOverflow.ellipsis,
                maxLines: 2,
                style: TextStyle(
                  color:
                      theme.brightness == Brightness.dark
                          ? Colors
                              .white // 深色模式下文字为白色
                          : Colors.black, // 浅色模式下文字为黑色
                ),
              ),
            );
          }).toList(),
    );
  }
}
